<template>
  <div class="app-container">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <el-page-header @back="handleBack" content="微信二维码管理"></el-page-header>
      <el-button 
        type="primary" 
        icon="el-icon-plus" 
        @click="handleAdd"
        class="add-btn"
      >
        新增二维码
      </el-button>
    </div>
    <!-- 二维码列表 -->
    <el-table
      v-loading="loading"
      :data="qrcodeList"
      border
      stripe
      style="width: 100%; margin-top: 10px"
    >
      <el-table-column type="index" label="序号" width="60"></el-table-column>
      <el-table-column prop="configName" label="二维码名称" min-width="150"></el-table-column>
     <!--  <el-table-column label="二维码图片" min-width="120">
        <template slot-scope="scope">
          <el-image
            :src="scope.row.configValue"
            :preview-src-list="[scope.row.configValue]"
            style="width: 80px; height: 80px"
            fit="contain"
          ></el-image>
        </template>
      </el-table-column> -->
      <el-table-column label="二维码图片" align="center" prop="configValue" width="100">
          <template slot-scope="scope">
            <image-preview :src="scope.row.configValue" :width="50" :height="50" />
          </template>

        </el-table-column>
      <el-table-column prop="sceneStr" label="场景值" min-width="120"></el-table-column>
      <el-table-column prop="expireSeconds" label="有效期(秒)" min-width="100">
        <template slot-scope="scope">
          {{ scope.row.expireSeconds || '永久有效' }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" min-width="160"></el-table-column>
      <el-table-column prop="status" label="状态" min-width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="180" fixed="right">
        <template slot-scope="scope">
          <el-button 
            size="mini" 
            type="text" 
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button 
            size="mini" 
            type="text" 
            icon="el-icon-delete"
            style="color: #ff4949"
            @click="handleDelete(scope.row.configId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="queryParams.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>
    </div>

    <!-- 新增/编辑二维码对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="form-container"
      >
        <el-form-item label="二维码名称" prop="configName">
          <el-input
            v-model="form.configName"
            placeholder="请输入二维码名称"
            maxlength="50"
          ></el-input>
        </el-form-item>
        <el-form-item label="场景值" prop="sceneStr">
          <el-input
            v-model="form.sceneStr"
            placeholder="请输入场景值，用于区分不同二维码"
            maxlength="64"
          ></el-input>
        </el-form-item>
        <el-form-item label="有效期" prop="expireSeconds">
          <el-input
            v-model="form.expireSeconds"
            placeholder="请输入有效期(秒)，永久有效请留空"
            type="number"
            min="0"
          ></el-input>
          <div class="form-hint">注：永久二维码无需填写，临时二维码默认为30天(2592000秒)</div>
        </el-form-item>

        <el-form-item label="二维码图片" prop="configValue">
          <image-upload v-model="form.configValue" />
        </el-form-item>
       <!--  <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listWechatQrcode,
  getWechatQrcode,
  addWechatQrcode,
  updateWechatQrcode,
  delWechatQrcode,
  downloadWechatQrcode
} from '@/api/wechatQrcode/wechatQrcode'

export default {
  configName: 'QrcodeManagement',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 表格数据
      qrcodeList: [],
      // 总条数
      total: 0,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        configName: '',
        status: ''
      },
      // 表单参数
      form: {
        configId: null,
        configName: '',
        sceneStr: '',
        expireSeconds: null,
        configValue: '',
        status: '1'
      },
      // 表单校验
      rules: {
        configName: [
          { required: true, message: '请输入二维码名称', trigger: 'blur' }
        ],
        sceneStr: [
          { required: true, message: '请输入场景值', trigger: 'blur' }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /**
     * 获取列表
     */
    getList() {
      this.loading = true
      listWechatQrcode(this.queryParams).then(response => {
        this.qrcodeList = response.data
        this.total = response.total
        this.loading = false
      })
    },
    /**
     * 分页大小改变
     */
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.queryParams.pageNum = 1
      this.getList()
    },
    /**
     * 当前页改变
     */
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getList()
    },
    /**
     * 新增按钮操作
     */
    handleAdd() {
      this.resetForm()
      this.open = true
      this.title = '新增微信二维码'
    },
    /**
     * 编辑按钮操作
     */
    handleEdit(row) {
      this.resetForm()
      const configId = row.configId
      getWechatQrcode(configId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '编辑微信二维码'
      })
    },
    /**
     * 状态改变
     */
    handleStatusChange(row) {
      const status = row.status
      const msg = status === 1 ? '启用' : '禁用'
      
      this.$confirm(`确定要${msg}该二维码吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateWechatQrcode({ ...row, status: status }).then(response => {
          this.$message.success(`${msg}成功`)
        }).catch(() => {
          row.status = row.status === 1 ? 0 : 1
        })
      }).catch(() => {
        row.status = row.status === 1 ? 0 : 1
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    /**
     * 删除按钮操作
     */
    handleDelete(configId) {
      this.$confirm('确定要删除该二维码吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delWechatQrcode(configId).then(response => {
          this.$message.success('删除成功')
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    /**
     * 下载二维码
     */
    handleDownload(configId) {
      downloadWechatQrcode(configId).then(response => {
        const blob = new Blob([response.data], { type: 'image/jpeg' })
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `qrcode-${configId}.jpg`
        document.body.appendChild(a)
        a.click()
        window.URL.revokeObjectURL(url)
        document.body.removeChild(a)
      })
    },
    /**
     * 提交表单
     */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          console.log(this.form.configId)
          if (this.form.configId != null) {
            updateWechatQrcode(this.form).then(response => {
              this.$message.success('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            // 添加创建时间
            const now = new Date()
            this.form.createTime = now
            this.form.updateTime = now
            
            addWechatQrcode(this.form).then(response => {
              this.$message.success('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /**
     * 重置表单
     */
    resetForm() {
      this.form = {
        configId: null,
        configName: '',
        sceneStr: '',
        expireSeconds: null,
        configValue: '',
        status: '1'
      }
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    /**
     * 取消按钮
     */
    cancel() {
      this.open = false
      this.resetForm()
    },
    /**
     * 返回上一页
     */
    handleBack() {
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.add-btn {
  margin-left: 10px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

.form-hint {
  color: #606266;
  font-size: 12px;
  margin-top: 5px;
}
</style>
